package bo;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Set;

import javax.xml.bind.ValidationException;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;


public abstract class WebService {
	
	
	private HttpServer webServer;
	private UrlReader urlReader;
	public abstract String comportamento();
	
	public WebService(String contesto, Set<String> params) throws ValidationException {
		try {
			int i = 0;
			for(String currentParam : params){
				if(!currentParam.matches("^[A-z]$")){
					throw new ValidationException("Param " + i + " don't match string pattern");
				}
				i++;
			}
			webServer = HttpServer.create(new InetSocketAddress(8000), 0);
			webServer.setExecutor(null);
			webServer.start();
			webServer.createContext("/" + contesto, new HandlerRisposta());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	
	
	private class HandlerRisposta implements HttpHandler {
		public void handle(HttpExchange t) throws IOException {
			
			
			urlReader.getUrlParameters("query");

//			Map<String, String> params = Utils.queryToMap(t.getRequestURI().getQuery());
//			Integer tempo = Integer.valueOf(params.get("t"));
//			if(tempo != 0){
//				//contatore.setText(String.valueOf((new SimpleDateFormat("mm:ss")).format(new Date(Integer.valueOf(tempo)))));
//				//titolo.setText(params.get("b"));
//				if(tempo<8000)
//					//lampeggiaOn();
//				else {
//					//lampeggiaOff();
//					//contatore.setForeground(Color.blue);
//				}
//			} else{
//				//reset();
//			}

//			String response = "Ho ricevuto: " + params.toString();
			
			String response = comportamento();
			
			t.sendResponseHeaders(200, response.length());
			OutputStream os = t.getResponseBody();
			os.write(response.getBytes());
			os.close();
		}
	}
	
	
	

}
